import { reactive, onMounted, onBeforeUnmount } from "vue";
import { debounce } from "@/utils/utils";

export function useScaleBox() {
  // 响应式状态
  const style = reactive({
    width: "1920",
    height: "1080",
    transform: "scaleY(1) scaleX(1) translate(-50%, -50%)",
  });

  // 获取缩放比例
  const getScale = () => {
    const w = window.innerWidth / style.width;
    const h = window.innerHeight / style.height;
    return { x: w, y: h };
  };

  // 设置缩放
  const setScale = () => {
    const scale = getScale();
    style.transform = "scaleY(" + scale.y + ") scaleX(" + scale.x + ") translate(-50%, -50%)";
  };

  // 防抖函数
  const debounceSetScale = debounce(() => {
    console.log("防抖函数");
    setScale();
  }, 100);

  // 组件挂载时的逻辑
  onMounted(() => {
    setScale();
    window.addEventListener("resize", debounceSetScale);
  });

  // 组件销毁前的逻辑
  onBeforeUnmount(() => {
    window.removeEventListener("resize", debounceSetScale);
  });

  // 返回响应式的 style 对象，以便在组件中使用
  return {
    style,
  };
}
